package com.treetao.union.mall.api.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.treetao.union.core.util.DateKit;
import com.treetao.union.db.Const;
import com.treetao.union.db.model.MallPSku;
import com.treetao.union.db.model.MallPSpu;
import com.treetao.union.db.model.MallSkill;
import com.treetao.union.db.model.MallSkillSku;
import com.treetao.union.db.model.vo.RestResponse;
import com.treetao.union.db.service.MallPAttrService;
import com.treetao.union.db.service.MallPServiceService;
import com.treetao.union.db.service.MallPSkuService;
import com.treetao.union.db.service.MallPSpuService;
import com.treetao.union.db.service.MallSkillService;
import com.treetao.union.mall.api.base.BaseCURDController;
import com.treetao.union.mall.api.vo.req.ReqParam;

import lombok.extern.slf4j.Slf4j;

/**
 * SKU商品
 * 
 * @author devm
 *
 */
@RestController
@RequestMapping("/mall/sku")
@Slf4j
public class MallSkuController extends BaseCURDController {
	@Autowired
	private MallPSkuService mallPSkuService;

	@Autowired
	private MallPSpuService mallPSpuService;

	@Autowired
	private MallPServiceService mallPServiceService;

	@Autowired
	private MallPAttrService mallPAttrService;

	@Autowired
	private MallSkillService mallSkillService;

	private static final String CacheKey = "_sku_detail_%s_";

	@Override
	protected IService<?> getCommonService() {
		return mallPSkuService;
	}

	@Override
	protected boolean setCommonDataAuth() {
		return false;
	}

	// 秒杀信息
	@GetMapping("skill")
	public RestResponse getSkill() {
		MallSkill skill = mallSkillService.getAvaliableSkill();
		if (skill != null) {
			List<MallSkillSku> skus = mallSkillService.getSkillSkus(skill.getId());
			if(skus!=null) {
				Map<String, Object> result = Maps.newHashMap();
				result.put("endTime", DateKit.formatDate(skill.getEndTime(), "yyyy-MM-dd HH:mm"));
				List<Map<String, Object>> list = Lists.newArrayList();
				for(MallSkillSku sku : skus) {
	        		MallPSku pSku = mallPSkuService.getById(sku.getSkuId());
	        		if(pSku!=null) {
	        			Map<String, Object> item = Maps.newHashMap();
	        			item.put("thumbnail",pSku.getThumbnail());
	        			item.put("name",pSku.getName());
	        			item.put("priceSale",pSku.getPriceSale());
	        			item.put("priceCost",pSku.getPriceCost());
	        			item.put("skuId",pSku.getId());
	        			item.put("skillId",sku.getSkillId());
	        			item.put("priceSkill", sku.getSkillPrice());
	        			list.add(item);
	        			
	        			//秒杀开始后，将库存信息放入redis中,因为开始后，秒杀不能在后台修改了
	        			if(!redisService.hHasKey(Const.skillRedisKey, String.valueOf(pSku.getId()))) {
	        				redisService.hset(Const.skillRedisKey, String.valueOf(pSku.getId()), sku.getNum());
	        			}
	        		}
	        	}
				if(skus.size()>0) {
					long mill = skill.getEndTime().getTime() - System.currentTimeMillis();
					//设定缓存失效时间(秒杀结束时间后30秒)
    				redisService.expire(Const.skillRedisKey, mill/1000 + 30);
				}
				result.put("skus", list);
				return RestResponse.success(result);
			}
		}
		return RestResponse.success();
	}

	@Override
	public void commonPageWhere(QueryWrapper<?> q, ReqParam param) {
		Long cataid = param.getLong("cataid");
		if (cataid != null) {
			q.eq("ref_twocata_id", cataid);
		}
		q.select("id", "name", "price_cost", "price_sale", "price_del", "thumbnail").orderByDesc("isrec", "saled_num");
	}

	/**
	 * 详情
	 * 
	 * @param param
	 * @return
	 */
	@Override
	public RestResponse detail() {
		ReqParam rp = getMappingReqParam();
		Long skuId = rp.getLong("id");
		Long skillId = rp.getLong("skillId");//秒杀ID
		String skuNo = rp.getValue("skuNo");

		if (skuId == null && StringUtils.isEmpty(skuNo)) {
			return RestResponse.failure("id或skuNo必填一个");
		}

		String cacheKey = null;
		if (skuId != null) {
			cacheKey = String.format(CacheKey, skuId);
		} else {
			cacheKey = String.format(CacheKey, skuNo);
		}

		
		MallSkillSku skillSku = null;
		if(skillId!=null) {
			skillSku = mallSkillService.getSkillSku(skillId, skuId);
		}
		
		MallPSku sku = null;
		if (redisService.hasKey(cacheKey)) {
			log.info("从Redis中获取SKU信息");
			sku = (MallPSku) redisService.get(cacheKey);
			if(skillSku!=null) {
				Map<String, Object> exts = sku.getExts();
				if(exts==null) {
					exts = Maps.newHashMap();
				}
				exts.put("skillSku",skillSku);
			}
			return RestResponse.success(sku);
		}
		if (skuId != null) {
			sku = mallPSkuService.getById(skuId);
		} else {
			sku = mallPSkuService.getSku(skuNo);
		}

		if (sku != null) {
			Map<String, Object> exts = new HashMap<String, Object>();
			// 关联SPU
			MallPSpu spu = mallPSpuService.getById(sku.getSpuId());
			if (spu != null) {
				spu.setCataname(null);
				spu.setDelFlag(null);
				spu.setId(null);
				spu.setRefOnecataId(null);
				spu.setRefTwocataId(null);
				spu.setSpuno(null);
			}
			exts.put("spu", spu);
			// 关联Service
			exts.put("services", mallPServiceService.getServices(sku.getId()));

			// 关联规格
			exts.put("attrs", mallPAttrService.getAttrs(sku.getId()));

			sku.setExts(exts);

			redisService.set(cacheKey, sku, 5 * 60);// 在缓存中存在5分钟
		}
		if(skillSku!=null) {
			Map<String, Object> exts = sku.getExts();
			if(exts==null) {
				exts = Maps.newHashMap();
			}
			exts.put("skillSku",skillSku);
		}
		return RestResponse.success(sku);
	}

}
